//
//  CreateJobInstallerDetailView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/6.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
import RxGesture
class CreateJobInstallerDetailView: CreateJobBaseView {
    var viewModel: CreateJobInstallerViewModel!
    lazy var installerTextField: TextFieldWithRequiredView = {
        let view = TextFieldWithRequiredView()
        view.textField.isEnabled = false
        view.textField.clearButtonMode = .never
        view.textField.showRightImageView("installation_list_search_down_arrow")
        return view
    }()
    lazy var designerTextField: TextFieldWithRequiredView = {
        let view = TextFieldWithRequiredView()
        view.textField.isEnabled = false
        view.textField.clearButtonMode = .never
        view.textField.showRightImageView("installation_list_search_down_arrow")
        return view
    }()
    lazy var electricianTextField: TextFieldWithRequiredView = {
        let view = TextFieldWithRequiredView()
        view.textField.isEnabled = false
        view.textField.clearButtonMode = .never
        view.textField.showRightImageView("installation_list_search_down_arrow")
        return view
    }()
    lazy var jobSiteInstructionTextView: TextViewWithRequiredView = {
        let view = TextViewWithRequiredView(.text, needCheckFlag: false)
        view.textView.placeholder = "Type your message"
        view.textView.limitLength = 1000
        view.textView.limitLabelFont = R.font.interRegular(size: 14)
        view.textView.limitLabelColor = UIColor(hexStr: "#292D3266")
        return view
    }()
    lazy var pickUpRequiredView: CreateJobInstallerPickUpRequiredView = {
        let view = CreateJobInstallerPickUpRequiredView()
        return view
    }()
    override func setUpContentView() {
        //installer
        let installerTitle = TitleLabelWithRequired(R.string.localizable.installer())
        self.contentView.addSubview(installerTitle)
        installerTitle.snp.makeConstraints { make in
            make.top.left.equalTo(Constant.AllOutMargin)
            make.height.width.greaterThanOrEqualTo(0)
        }
        self.contentView.addSubview(installerTextField)
        installerTextField.snp.makeConstraints { make in
            make.top.equalTo(installerTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(installerTitle)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.equalTo(DIYTextField.height)
        }
        //designer
        let designerTitle = TitleLabelWithRequired(R.string.localizable.designer())
        self.contentView.addSubview(designerTitle)
        designerTitle.snp.makeConstraints { make in
            make.top.equalTo(installerTextField.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(installerTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        self.contentView.addSubview(designerTextField)
        designerTextField.snp.makeConstraints { make in
            make.top.equalTo(designerTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.height.equalTo(installerTextField)
        }
        
        //electrician
        let electricianTitle = TitleLabelWithRequired(R.string.localizable.electrician())
        self.contentView.addSubview(electricianTitle)
        electricianTitle.snp.makeConstraints { make in
            make.top.equalTo(designerTextField.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(installerTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        self.contentView.addSubview(electricianTextField)
        electricianTextField.snp.makeConstraints { make in
            make.top.equalTo(electricianTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.height.equalTo(installerTextField)
        }
        //electrician
        let jobSiteInstructionTitle = ContentLabel(text: R.string.localizable.jobSiteInstructionsForTheInstaller(), hexStr: Constant.RequiredTitleColorHexStr)
        self.contentView.addSubview(jobSiteInstructionTitle)
        jobSiteInstructionTitle.snp.makeConstraints { make in
            make.top.equalTo(electricianTextField.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(installerTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        self.contentView.addSubview(jobSiteInstructionTextView)
        jobSiteInstructionTextView.snp.makeConstraints { make in
            make.top.equalTo(jobSiteInstructionTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalTo(installerTextField)
            make.height.equalTo(150)
        }
        self.contentView.addSubview(pickUpRequiredView)
        pickUpRequiredView.snp.makeConstraints { make in
            make.top.equalTo(jobSiteInstructionTextView.snp.bottom)
            make.left.right.equalTo(installerTextField)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.lessThanOrEqualTo(-Constant.AllOutMargin)
        }
        //点击Add address跳转到选择相应的view，方便用户填写pick up address
        self.pickUpRequiredView.scrollToBottomClosure = {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.layoutIfNeeded()//会强制重绘并等待完成。
            strongSelf.scrollView.scrollToBottom()
        }
        self.pickUpRequiredView.scrollToAddAddressViewClosure = {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.layoutIfNeeded()//会强制重绘并等待完成。
            let pointOnScrollView = strongSelf.pickUpRequiredView.addressContent.convert(strongSelf.pickUpRequiredView.addAddressBtn.frame.origin, to: strongSelf.scrollView)
            strongSelf.scrollView.scrollToView(point: pointOnScrollView, animated: true)
        }
        self.initBinding()
    }
    private func initBinding(){
        //选择installer
        installerTextField.rx.tapGesture().when(.recognized).subscribe { _ in
            Tool().showSearchInstallerView(type: .installer, title: R.string.localizable.installer()) { [weak self] (model) in
                self?.viewModel.installerID = model.id
                self?.viewModel.installerName = model.name
                self?.installerTextField.textField.text = model.name
            }
        }.disposed(by: self.disposeBag)
        //选择designer
        designerTextField.rx.tapGesture().when(.recognized).subscribe { _ in
            Tool().showSearchInstallerView(type: .designer, title: R.string.localizable.designer()) { [weak self] (model) in
                self?.viewModel.designerID = model.id
                self?.viewModel.designerName = model.name
                self?.designerTextField.textField.text = model.name
            }
            
        }.disposed(by: self.disposeBag)
        //选择electrician
        electricianTextField.rx.tapGesture().when(.recognized).subscribe { _ in
            Tool().showSearchInstallerView(type: .electrician, title: R.string.localizable.electrician()) { [weak self] (model) in
                self?.viewModel.electricianID = model.id
                self?.viewModel.electricianName = model.name
                self?.electricianTextField.textField.text = model.name
            }
        }.disposed(by: self.disposeBag)
        //job site instruction for the installer
        jobSiteInstructionTextView.endEditingClosure = {[weak self] data in
            self?.viewModel.installer_job_site_instruction = data
        }
    }
    func setData(_ model: CreateJobInstallerViewModel){
        self.viewModel = model
        self.installerTextField.textField.text = viewModel.installerName
        self.designerTextField.textField.text = viewModel.designerName
        self.electricianTextField.textField.text = viewModel.electricianName
        self.jobSiteInstructionTextView.textView.text = viewModel.installer_job_site_instruction
        self.pickUpRequiredView.setData(self.viewModel)
        //
        self.checkEverythingValid()
    }
    //MARK: - 必填项数据绑定控制continue btn是否可用
    private func checkEverythingValid(){
        //1.installation type
        let installerValid = self.installerTextField.textField.rx.observe(String.self, "text").map({($0 ?? "").count > 0}).share(replay: 1)
        let designerValid = self.designerTextField.textField.rx.observe(String.self, "text").map({($0 ?? "").count > 0}).share(replay: 1)
        let electricianValid = self.electricianTextField.textField.rx.observe(String.self, "text").map({($0 ?? "").count > 0}).share(replay: 1)
        //2.pick up required
        let pickupReqeuiredValid = self.pickUpRequiredView.pickUpReqiredSwitchBtn.rx.observe(Int.self, "tag").map({$0 == 1}).share(replay: 1)
        let pickupAddressValid = self.pickUpRequiredView.pickUpAddressTextField.textField.rx.observe(String.self, "text").map({($0 ?? "").count > 0}).share(replay: 1)
        //整个installationType 信息是否有效
        let everythingValid = Observable.combineLatest(
            installerValid,
            designerValid,
            electricianValid,
            pickupReqeuiredValid,
            pickupAddressValid
        ) { ($0 && $1 && $2) && (!$3 || ($3 && $4))}
        .share(replay: 1)
        
        everythingValid.subscribe { [weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid{
                strongSelf.continueBtn.enableBtn()
            }else{
                strongSelf.continueBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
}
